package com.tanx.cqrs.infrastructure.spring.event.handler;

import com.tanx.cqrs.event.handler.EventHandlerInstance;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.security.InvalidParameterException;

/**
 * 事件处理器实例
 */
@Data
@NoArgsConstructor
public class SpringBeanEventHandlerInstance implements EventHandlerInstance {
    private Class eventClass;
    private Object bean;
    private Method method;

    public SpringBeanEventHandlerInstance(Object bean, Method method) {
        this.bean = bean;
        this.method = method;
        Parameter[] parameters = method.getParameters();
        if (parameters.length != 1) {
            throw new InvalidParameterException("事件处理器(EventHandler)参数必须只有事件一个");
        }
        this.eventClass = parameters[0].getType();
    }

    @Override
    public void invoke(Object event) throws Exception {
        method.invoke(bean, event);
    }
}
